package com.weiyi.mashangzhu.Roomer.Activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.hyphenate.chat.EMClient;
import com.squareup.okhttp.Request;
import com.weiyi.mashangzhu.API.API;
import com.weiyi.mashangzhu.Application.MyApp;
import com.weiyi.mashangzhu.Base.BaseActivity;
import com.weiyi.mashangzhu.R;
import com.weiyi.mashangzhu.Utils.IsPhoneNum;
import com.weiyi.mashangzhu.Utils.LoadingDialog;
import com.weiyi.mashangzhu.Utils.SPUtils;
import com.weiyi.mashangzhu.Utils.T;
import com.weiyi.mashangzhu.Utils.UiUtil;
import com.weiyi.mashangzhu.easemob.db.ChatDao;
import com.weiyi.mashangzhu.listener.CallBackListener;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class BindActivity extends BaseActivity {

    @BindView(R.id.register_phone)
    EditText registerPhone;
    @BindView(R.id.register_verify_code)
    EditText registerVerifyCode;
    @BindView(R.id.register_get_code)
    Button registerGetCode;
    int time = 60;
    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 1) {
                if (time >= 2) {
                    time -= 1;
                    registerGetCode.setText("稍后" + time + "s...");
                    handler.sendEmptyMessageDelayed(1, 1000);
                    registerGetCode.setEnabled(false);
                } else {
                    time = 60;
                    registerGetCode.setTextColor(getResources().getColor(R.color.colorPrimary));
                    registerGetCode.setEnabled(true);
                    registerGetCode.setText("获取验证码");
                }
            }
            return false;
        }
    });
    private String wxToken;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bind);
        ButterKnife.bind(this);
        wxToken = getIntent().getStringExtra("wxToken");
    }

    public static void start(Context context, String wxToken) {
        Intent intent = new Intent(context, BindActivity.class);
        intent.putExtra("wxToken", wxToken);
        context.startActivity(intent);
    }

    @Override
    public void initView() {
        super.initView();
    }


    @OnClick({R.id.back, R.id.register_get_code, R.id.register_finish})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.register_get_code:
                if (IsPhoneNum.isMobileNO(registerPhone.getText() + "") == false) {
                    T.showShort(this, "请输入有效手机号码");
                } else {
                    OkHttpUtils.get().url(API.BaseApi_R + "sendWeixincheckCode")
                            .addParams("users.uAccount", registerPhone.getText().toString().trim())
                            .build()
                            .execute(new StringCallback() {
                                @Override
                                public void onError(Request request, Exception e) {

                                }

                                @Override
                                public void onResponse(String response) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String status = jsonObject.getString("status") + "";
                                        if (status.equals("0")) {
                                            registerGetCode.setTextColor(getResources().getColor(R.color.colorGrey));
                                            registerGetCode.setText("稍后" + time + "s...");
                                            handler.sendEmptyMessageDelayed(1, 1000);
                                        }else {
                                            T.showShort(BindActivity.this,jsonObject.getString("msg"));
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }

                                }
                            });

                }
                break;
            case R.id.register_finish:
                if ((registerPhone.getText() + "").equals("")) {
                    T.showShort(this, "手机号不能为空");
                } else {
                    if (IsPhoneNum.isMobileNO(registerPhone.getText() + "") == false) {
                        T.showShort(this, "请输入有效手机号码");
                    } else {
                        if ((registerVerifyCode.getText() + "").equals("")) {
                            T.showShort(this, "短信验证码不能为空");
                        } else {
                            if (MyApp.clientid != null) {
                                LoadingDialog.show(BindActivity.this);
                                OkHttpUtils.get().addParams("uAccount", registerPhone.getText() + "")
                                        .addParams("uCid", MyApp.clientid)
                                        .addParams("uWeixin", wxToken)
                                        .addParams("cNumber", registerVerifyCode.getText() + "")
                                        .url(API.BaseApi_R + API.Login_Api)
                                        .build().execute(new StringCallback() {
                                    @Override
                                    public void onError(Request request, Exception e) {
                                        LoadingDialog.dismiss(BindActivity.this);
                                        T.showShort(BindActivity.this,"数据获取失败，请稍后再试");
                                    }

                                    @Override
                                    public void onResponse(String response) {

                                        Log.e("seeeeeeeeeeeee","==="+response);
                                        try {
                                            JSONObject jsonObject = new JSONObject(response);
                                            String status = jsonObject.getString("status") + "";
                                            String msg = jsonObject.getString("msg");
                                            if (status.equals("0")){

                                                JSONObject jsonObject1=jsonObject.getJSONObject("data");
                                                String token = jsonObject1.getString("token");
                                                String uNickname = jsonObject1.getString("uNickname");
                                                String uHead = jsonObject1.getString("uHead");
                                                String uPassword = jsonObject1.getString("uPassword");
                                                // APP登录成功后，接着登录环信
                                                if (token != null) {
                                                    String[] split = token.split("@");
                                                    if (split.length > 1) {
                                                        String userAccount = split[1];
                                                        if (userAccount != null) {
                                                            saveNickAndAvatar(userAccount, uNickname, uHead);
                                                            logoutEaseMob(userAccount,uPassword , msg, token);
//                                                            loginEaseMob(userAccount, uPassword, msg, token);
//                                                            Md5Utils.getEncryption(uPassword)
                                                        }
                                                    }
                                                }
                                            } else {
                                                LoadingDialog.dismiss(BindActivity.this);
                                                T.showShort(BindActivity.this, msg);
                                            }
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                });
                            } else {
                                T.showShort(BindActivity.this, "推送信息初始化失败，请稍后再试");
                            }
                        }
                    }
                }
                break;
        }
    }


    private void saveNickAndAvatar(String userAccount, String uNickname, String uHead) {
        ChatDao chatDao = new ChatDao(this);
        if (!chatDao.isExist(userAccount)) {
            chatDao.add(userAccount, uNickname, uHead);
        } else {
            chatDao.update(userAccount, uNickname, uHead);
        }
    }
    private void logoutEaseMob(final String uAccount, final String uPassword, final String msg, final String data) {
        EMClient.getInstance().logout(true, new CallBackListener() {
            @Override
            public void onMainSuccess() {
                SPUtils.put(BindActivity.this, "token", "");
                SPUtils.put(BindActivity.this, "isLogin", "0");
                loginEaseMob(uAccount, uPassword, msg, data);
            }

            @Override
            public void onMainError(int code, String message) {
                LoadingDialog.dismiss(BindActivity.this);
                T.showShort(BindActivity.this, "error:" + code + " " + message);
            }
        });
    }
    private void loginEaseMob(String uAccount, String uPassword, final String msg, final String data) {

        EMClient.getInstance().login(uAccount, uPassword, new CallBackListener() {
            @Override
            public void onMainSuccess() {
                LoadingDialog.dismiss(BindActivity.this);
                loginSuccess(msg, data);
            }
            @Override
            public void onMainError(int code, String message) {
                LoadingDialog.dismiss(BindActivity.this);
                T.showShort(BindActivity.this, "error:" + code + " " + message);
            }
        });
    }

    private void loginSuccess(String msg, String data) {
        EMClient.getInstance().groupManager().loadAllGroups();
        EMClient.getInstance().chatManager().loadAllConversations();

        //登录成功
        T.showShort(BindActivity.this, msg);
        //存储token
        SPUtils.put(BindActivity.this, "token", data);
        SPUtils.put(BindActivity.this, "isLogin", "1");
//                if (string.equals("变身房东")) {
//                    UiUtil.startActivity(LoginActivity.this, MainActivity_L.class);
//                } else {
        UiUtil.startActivity(BindActivity.this, MainActivity_R.class);
//                }
        finish();
    }
}
